package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.comment.domain.UserInfoAttention;
import cn.wolfcode.luowowo.comment.service.IUserInfoAttentionService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文件上传控制器
 */
@Controller
public class UploadController {

    @Value("${file.path}")
    private String basePath;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private IUserInfoAttentionService userInfoAttentionService;
    //上传图片
    @RequestMapping("/coverImageUpload")
    @ResponseBody
    public Object coverImageUpload(MultipartFile pic){
        String upload = UploadUtil.upload(pic, basePath);
        return upload;
    }


    @RequestMapping("/upload/file")
    @ResponseBody
    //上传头像
    public Object upload(MultipartFile files, @UserParam UserInfo userInfo, HttpServletRequest request, HttpServletResponse response){
        String upload = UploadUtil.upload(files, basePath);
        String photo = "/"+upload;
        userInfoService.uploadHeadImgUrl(photo,userInfo.getId());
        UserInfo user = userInfoService.get(userInfo.getId());
        String token = CookieUtil.getCookie(request, response);
        UserInfo s = userInfoRedisService.getUserByToken(token);
        userInfoRedisService.setTokenByUser(token,user);

        //更新头像时更新mongodb

        List<UserInfoAttention> mongodbUser = userInfoAttentionService.findAllBybeUserId(userInfo.getId());
        for (UserInfoAttention attention : mongodbUser) {
            attention.setHeadUrl(photo);
            userInfoAttentionService.save(attention);
        }


        request.getSession().setAttribute("userInfo", user);
        return upload;
    }

}
